package com.example.onlinemallsystem.controller;

import com.example.onlinemallsystem.service.ex.ServiceException;
import com.example.onlinemallsystem.util.JsonResult;
import com.example.onlinemallsystem.service.ex.*;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;

public class BaseController {
    //请求处理方法，返回值就是需要传递给前端的数据
    //自动将异常对象传递给此方法的参数列表上
    //当前项目只要产生异常，就拦截到此方法中，以此方法充当请求处理方法，方法的返回值给到前端
    // 处理用户名重复异常
    protected final Integer getIdFromSession(HttpSession session) {
        Object userIdObj = session.getAttribute("userId");
        if (userIdObj == null) {
            return null;
        }
        return Integer.valueOf(userIdObj.toString());
    }
    protected final String getUsernameFromSession(HttpSession session) {
        Object usernameObj = session.getAttribute("username");
        if (usernameObj == null) {
            return null; // 或返回空字符串，根据业务需求决定
        }
        return usernameObj.toString();
    }
    @ExceptionHandler({ServiceException.class})
    public  JsonResult<Void> handleException(Throwable e) {
        JsonResult<Void> result = new JsonResult<Void>(e);
        if (e instanceof UsernameDuplicatedException) {
            result.setState(4000);
            result.setMessage("用户名被占用");
        }else if (e instanceof UserNotFoundException) {
            result.setState(5000);
            result.setMessage("用户数据不存在");
        } else if (e instanceof PasswordNotMatchException) {
            result.setState(5001);
            result.setMessage("用户密码错误");
        } else if (e instanceof InsertException) {
            result.setState(5002);
            result.setMessage("插入时产生的错误异常");
        }else if (e instanceof UpdateException) {
            result.setState(5003);
            result.setMessage("更新时产生的错误异常");
        }
        return result;
    }
}
